package com.example.logintest.controller;

import com.example.logintest.bean.User;
import com.example.logintest.service.LoginService;
import com.example.logintest.util.CreateJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/test")
@CrossOrigin(origins = "*",maxAge = 3600)
public class LoginController {

    @Autowired
    LoginService loginService;
    @RequestMapping(value = "/login")
    public Object login(@RequestParam(value = "username")String username,
                        @RequestParam(value = "password")String password){
        Map<String,Object> map =new HashMap<>();
        if(username == null || password== null){
            map.put("code", 100);
            map.put("msg", "can not be empty");
        }else{
            User user = loginService.login(username);
            if(user == null){
                map.put("code", 101);
                map.put("msg", "no such user");
            }else{
                if(password.equals(user.getPassword())){
                    String token = CreateJWT.getToken(user);
                    map.put("code", 200);
                    map.put("user", user);
                    map.put("token", token);
                    map.put("msg", "success!");
                }else {
                    map.put("code", 102);
                    map.put("msg", "fail");
                }
            }



        }


        return map;
    }
}
